﻿<?php

/*
 * Copyright (c) 2010 DC Team
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files(the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

if (!defined('DC')) {
	die('It\'s allowed!');
}

//数据库同步工具 公共函数

/* 连接数据库 返回数据库连接数组
 * param $dbIds     数据库标识
 * param $g_db_conf 数据库配置数组
 */ 
function mysqlConnect($dbIds){
	global $g_db_conf;
	$version = $_SERVER['SERVER_NAME'];
	if(!is_array($dbIds)){
		@$db = new mysqli($g_db_conf[$version][$dbIds]['db_host'], $g_db_conf[$version][$dbIds]['db_user'], $g_db_conf[$version][$dbIds]['db_pass'], $g_db_conf[$version][$dbIds]['db_name'], $g_db_conf[$version][$dbIds]['db_port']);
		//check_pri($dbIds, $db);
		
		if (mysqli_connect_errno()) {
			exit ($dbIds.'连接出错');
		}else {
			$db ->query('SET NAMES UTF8');
			$g_db[$dbIds] = $db;
		}
	}else {
		foreach ($dbIds as $dbId){
			@$db = new mysqli($g_db_conf[$version][$dbId]['db_host'], $g_db_conf[$version][$dbId]['db_user'], $g_db_conf[$version][$dbId]['db_pass'], $g_db_conf[$version][$dbId]['db_name'], $g_db_conf[$version][$dbId]['db_port']);
			//check_pri($dbId, $db);
			if (mysqli_connect_errno()) {
				exit ($dbId.'连接出错');
			}else {
				$db ->query('SET NAMES UTF8');
				$g_db[$dbId] = $db;
			}
		}
	}
	return $g_db;
}

/*数据库权限检测
 *@ param array $dbId  数据库标识数组
*/

function check_pri ($dbIds, $db){
	global $g_db_conf;
	$version = $_SERVER['SERVER_NAME'];
	//权限检测
	$row = $db->query("show grants for {$g_db_conf[$version][$dbIds]['db_user']}@{$g_db_conf[$version][$dbIds]['db_host']}");
	$result = $row->fetch_row();
	$str = $result[0];
	$arr = array('insert', 'update', 'delete', 'create', 'drop', 'alter', 'show view', 'show databases');//需要的权限数组
	if (!stristr($str, 'ALL PRIVILEGES')) {
		$n = 0;
		foreach ($arr as $value){
			if (!stristr($str, $value)) {
				$n ++;
			}
		}
		if ($n > 0) {
			exit($dbIds.'权限不足');
		}
	}

}

/*获取数据库表名称及每张表的字段
 *@ param array $dbId  数据库标识数组
 *@ param $tab         0 只取出表 1取出表及其结构
 *@ param $net         1 远程对比数据
*/

function checkDatabase ($dbIds, $tab=1, $net=0){
	global $g_db, $configs;
	
	if(!is_array($dbIds)){
		$dbId[] = $dbIds ;
	}else {
		$dbId = $dbIds;
	}
	
	foreach ($dbId as $key){
		//读取所有的表
		$sql = "SHOW TABLES";
		$row = $g_db[$key]->query($sql);
	
		if ($tab == 1) {
			while($result = $row -> fetch_array()){
				if (!stristr($result[0], 'backup0_0')) {
					//读取每张表的字段
					$sql2 = "DESCRIBE {$result[0]}";
					$row2 = $g_db[$key]->query($sql2);
					while($result2 = $row2->fetch_array()){
//						if ( $result[0] == 'blackkey' ){
//							$rr2 = $g_db[$key]->query("show create table {$result[0]}");
//							$result7 = $rr2->fetch_array();						
//						}
						//加入索引
						$sy = '';
						if (!empty($result2[3])) {
							$sy = '<font color=green>['.$result2[3].']</font>';
						}
						
						
						if ($net == 1) {
							$database[$key][$result[0]][] = array($result2[0], '<font color=blue>'.$result2[1].'</font> '.$sy, $result2['Default'], $result2['Null']);
						}elseif ( $net != 1 && !in_array($result[0], $configs['field']) && !in_array($result[0], $configs['index']) ){
							$database[$key][$result[0]][] = array($result2[0], '<font color=blue>'.$result2[1].'</font> '.$sy);
						}elseif ( $net != 1 && !in_array($result[0], $configs['field']) && in_array($result[0], $configs['index']) ){
							$database[$key][$result[0]][] = array($result2[0], '<font color=blue>'.$result2[1].'</font> ');
						}elseif ( $net != 1 && in_array($result[0], $configs['field']) && !in_array($result[0], $configs['index']) ){
							$database[$key][$result[0]][] = array($result2[0], $sy );
						}elseif ( $net != 1 && in_array($result[0], $configs['field']) && in_array($result[0], $configs['index']) ){
							$database[$key][$result[0]][] = array($result2[0], '');
						}
						
					}
				}
				
			}
		}else {
			while($result = $row -> fetch_array()){
				if (!strpos($result[0], 'backup0_0')) {
					$database[$key][]=$result[0];
				}
			}
		}		
	}
	return $database;
}

/*获取数据库表名称及每张表的字段
 *@ param array $dbId  数据库标识数组
 *@ param $table       表名
*/

function checkDatabaseNew ($dbId, $tablename){
	global $g_db, $configs;

	if (!stristr($tablename, 'backup0_0')) {
		//读取每张表的字段
		$sql2 = "DESCRIBE {$tablename}";
		$row2 = $g_db[$key]->query($sql2);
		while($result2 = $row2->fetch_array()){
			//加入索引
			$sy = '';
			if (!empty($result2[3])) {
				$sy = '<font color=green>['.$result2[3].']</font>';
			}

			if ( !in_array($tablename, $configs['field']) && !in_array($tablename, $configs['index']) ){
				$database[$key][$tablename][] = array($result2[0], '<font color=blue>'.$result2[1].'</font> '.$sy);
			}elseif ( !in_array($tablename, $configs['field']) && in_array($tablename, $configs['index']) ){
				$database[$key][$tablename][] = array($result2[0], '<font color=blue>'.$result2[1].'</font> ');
			}elseif ( in_array($tablename, $configs['field']) && !in_array($tablename, $configs['index']) ){
				$database[$key][$tablename][] = array($result2[0], $sy );
			}elseif ( in_array($tablename, $configs['field']) && in_array($tablename, $configs['index']) ){
				$database[$key][$tablename][] = array($result2[0], '');
			}

		}
	}
	return $database;
}

/*获取数据库每张表的字段
 *@ param $tabId        表名称
 *@ param $dbId        数据库标识
*/
function checkTable($tabId, $dbId){
	global $g_db;
	if(!is_array($tabId)){
		$tabIds[] = $tabId ;
	}else {
		$tabIds = $tabId;
	}
	
	foreach ($tabIds as $value){
		//读取每张表的字段
		$sql2 = "DESCRIBE $value";
		$row2 = $g_db[$dbId]->query($sql2);
		if (!$row2) {
			exit('请检查你的快捷查询是否设置正确');
		}
			
		while($result2 = $row2->fetch_row()){
			$table[$value][] = array($result2[0], '<font color=blue>'.$result2[1].'</font>');
		}
	}
	return $table;
}

/*自定义数组比较函数
 *@ param array $v1  数组的一个单元
 *@ param array $v2  数组的一个单元
*/
function myDiff ($v1, $v2){
	if ($v1[0] == $v2[0] && $v1[1] == $v2[1]) {
		return 0;
	}
	if ($v1[0] > $v2[0]) {
		return 1;
	}else {
		return -1;
	}
}

/*输出字段比较结果的函数
 *@ param array $arr  一个二维数组
*/
function myImplode ($arr){
	if (count($arr)) {
		$str = '<font color=red>';
		foreach ($arr as $key => $value){
			$str .= $value[0].' '.$value[1].',<br /> ';
		}
		$str .= '</font>';
	}else {
		$str = '';
	}	
	return $str;
}

/*备份数据库
 *@ param $is_back  是否备份
 *@ param $tabId  备份的表名
 *@ param $dbId   数据库标识
*/
function backupData ($is_back=1, $tabId, $dbId){
	global $g_db;
	if ($is_back) {
		$name = 'backup0_0'.$tabId.date('0_0Ymd_His');
		$g_db[$dbId]->query("CREATE TABLE $name SELECT * FROM $tabId");
	}
}

/*比较数据库
 *@ param $dbdata               要比较的数据库数据
 *@ param $maindata             主数据库数据
 *@ param $dbId $dbmainId       数据库id
 *@ param $type                 1 字段同步 2 数据同步
*/
function compareDb ($dbdata, $maindata, $dbId, $dbmainId , $type = '1'){
	global $g_db, $configs;
	//比较数据库过程
	foreach ($dbdata as $key => $value){
		//与标准数据库比较,得出各种集合		
		$lack      = @array_diff_key($maindata[$dbmainId], $value);//缺少
		$more      = @array_diff_key($value, $maindata[$dbmainId]);//多余
		$intersect = @array_intersect_key($value, $maindata[$dbmainId]);//交集
		//用于同步表结构时判断
		$_SESSION['diff'][$key] = array('lack' => $lack, 'more' => $more, 'interset' => $intersect);
		
		if ($type == 1) {
			//以下分别对三种集合进行处理
			foreach ($lack as $k => $val){
				$diffen[$key][$k] = array('exist' => '缺少', 'lack' => '未比较', 'more' => '未比较');
			}
			foreach ($more as $k => $val){
				$diffen[$key][$k] = array('exist' => '多余', 'lack' => '未比较', 'more' => '未比较');
			}
		}
		
		foreach ($intersect as $k => $val){
			//字段对比
			$field_lack  = @array_udiff($maindata[$dbmainId][$k], $val, 'myDiff');//字段缺少
			$field_more  = @array_udiff($val, $maindata[$dbmainId][$k], 'myDiff');//字段多余			
			
			//用于同步字段时判断
			$_SESSION['diff'][$key]['field_lack'][$k] = $field_lack;
			$_SESSION['diff'][$key]['field_more'][$k] = $field_more;
			
			//特定表进行条数对比
			$num  = 0;
			$num2 = 0;
			if (@in_array($k, $configs['table'])) {
				$sql  = "SELECT * FROM $k";
				$row  = $g_db[$key]->query($sql);
				$num  = $row->num_rows;
				$row2 = $g_db[$dbmainId]->query($sql);
				$num2 = $row2->num_rows;
			}

			if ($type != 1){
				$diffen[$key][$k] = array('exist' => '存在', 'lack' => '一致', 'more' => '一致'); 
			}		
			
			
			//判断顺序是否一致
			
			foreach ($maindata[$dbmainId][$k] as $kk => $vv){
				$main = array($kk => $vv[0]);
			}
			foreach ($val as $kk => $vv){
				$bb = array($kk => $vv[0]);
			}
			$order = '';
			$_SESSION['order'] = '';
			if(array_diff_assoc($main, $bb)){
				//$diffen[$key][$k]['exist'] = '字段顺序不一致';
				$order = '<font color=blue>字段顺序不一致</font>';
				$_SESSION['order'][$key][] = $k;
			}
			
			//返回字段及条数不一样的表结果
			if (count($field_lack) > 0 || count($field_more) > 0 || $num != $num2 || $order) {
				$str = '';
				if($num != $num2){
					$str = '<font color=red>(当前:'.$num.' 主库:'.$num2.')</font>';
				}
				$field_lack  = myImplode($field_lack);
				$field_more  = myImplode($field_more);		
							
				$diffen[$key][$k] = array('exist' => '存在 '.$order.$str, 'lack' => $field_lack, 'more' => $field_more); 
				$str = '';
			}	

		}
		if ($type == 1) {
			if(count($intersect) > 0 && @count($diffen[$key]) == 0){
				$diffen[$key]['每张表及其结构'] = array('exist' => '完全一致', 'lack' => '', 'more' => '');				
			}
		}
	}
	return $diffen;
}


/*一键同步
 *@ param $dbdata               要同步的数据库数据
 *@ param $maindata             主数据库数据
 *@ param $dbId $dbmainId       数据库id
*/
function autorsyncDb($dbdata, $maindata, $dbId, $dbmainId){
	global $g_db, $configs;
	//比较数据库过程
	$result = '';
	foreach ($dbdata as $key => $value){
	    //与标准数据库比较,得出各种集合
	    $lack      = @array_diff_key($maindata[$dbmainId], $value);//缺少
	    $intersect = @array_intersect_key($value, $maindata[$dbmainId]);//交集
	    $result .= '<font color="red">'.$key.'数据库同步结果:</font><br>';
	    //以下分别对三种集合进行处理
	    foreach ($lack as $k => $val){
	        $sql = "SHOW CREATE TABLE $k";
	        $row = $g_db[$dbmainId]->query($sql);
	        $rs = $row->fetch_assoc();
	        $sqltext = $rs['Create Table'];
	        $g_db[$key]->query($sqltext);
	        if ( $g_db[$key]->errno ){
	            $result .= '添加'.$k.'表失败<br>';
	        } else {
	            $result .= '添加'.$k.'表成功<br>';
	        }
	    }
	    $fl = '0';
	    foreach ($intersect as $k2 => $val2){
	        //字段对比
	        $field_lack  = @array_udiff($maindata[$dbmainId][$k2], $val2, 'myDiff');//字段缺少
	        if (count($field_lack) > '0') {
	            $fl = '1';
	            $tablefl[$k2] = $field_lack;
	        }
	    }
	    //字段处理
	    if ($fl == '1') {
    	    foreach ($tablefl as $k => $val) {
    	        foreach ($val as $k2 => $val2){
    				$need[] = $val2[0];
    			}
    			
    	        $sql = "DESCRIBE $k";
    	        $row = $g_db[$dbmainId]->query($sql);
              
    	        //取出$dbId的字段集,用于判断是字段不一样是由名称还是字符类型造成的
    	        $r = $g_db[$key]->query("DESCRIBE $k");
    	        while ($res = $r->fetch_array()){
    	            $out[] = $res[0];
    	            $field[$res[0]] = $res[1];
    	            $keysearch[$res[0]] = $res[3];//判断是否已有索引
    	        }
    
    	        $sqltext = "ALTER TABLE $k ";
    
    	        $preField = '';//用于记录前一个字段
    
    
    	        while ($rs2= $row->fetch_assoc()){
    	            //属于字段有差别的集合
    	            if (@in_array($rs2['Field'], $need)) {
    	                //属于字段有差别的集合
    	                $do  = "ADD ";
    	                //字符类型不一样,语句采用change
    	                if (@in_array($rs2['Field'], $out)) {
    	                    $do  = "CHANGE {$rs2['Field']}";
    	                }
    	                $sqltext .= "{$do} {$rs2['Field']} {$rs2['Type']} ";

    	                if (!stristr($rs2['Type'], 'int') && !stristr($rs2['Type'], 'decimal') && !stristr($rs2['Type'], 'float') && !stristr($rs2['Type'], 'double')) {
    	                    $sqltext .= "CHARACTER SET utf8 COLLATE utf8_general_ci ";
    	                }
    	                if ($rs2['Null'] == 'NO') {
    	                    $sqltext .= 'NOT NULL ';
    	                }else {
    	                    $sqltext .= 'NULL ';
    	                }

    	                if ($rs2['Default'] != '') {
    	                    $sqltext .= "DEFAULT '{$rs2['Default']}' ";
    	                }

    	                if (!empty($preField)) {
    	                    $sqltext .= " AFTER $preField,";
    	                }else {
    	                    $sqltext .= ",";
    	                }
    	                //如果有索引,且要导入的表不存在此索引
    	                if (!empty($rs2['Key']) && ((isset($keysearch[$rs2['Field']]) && $keysearch[$rs2['Field']] == '') || !isset($keysearch[$rs2['Field']]))){
    	                    if ( $rs2['Key'] == 'PRI' ){
    	                        $sqltext .= " ADD PRIMARY KEY ({$rs2['Field']}),";
    	                    }elseif ( $rs2['Key'] == 'UNI' ){
    	                        $sqltext .= " ADD UNIQUE ({$rs2['Field']}),";
    	                    }elseif ( $rs2['Key'] == 'MUL' ){
    	                        $sqltext .= " ADD INDEX ({$rs2['Field']}),"; //最后一位必须为','，不能为空格
    	                    }
    	                }
    	            }
    	            $preField = $rs2['Field'];//记录前一字段
    	        }
    
    	        $sqltext = substr($sqltext, 0, -1);
    	        $g_db[$key]->query($sqltext);
    	        if ( $g_db[$key]->errno ){
    	            $result .= '同步表'.$k.'字段失败，请检查表字段是否符添加要求<br>';
    	        } else {
    	            $result .= '同步表'.$k.'字段成功<br>';
    	        }
    	    }
	    }
	}
	return $result;
}

/*比较表
 *@ param $table      要比较的表
 *@ param $maintable  主表
*/
function compareTable ($table, $maintable){
	
	foreach ($table as $key => $value){		
		$lack = array_udiff($maintable, $value, 'myDiff');//缺少的字段
		$more = array_udiff($value, $maintable, 'myDiff');//多余的字段
		$diffen[$key]['lack'] = myImplode($lack);		
		$diffen[$key]['more'] = myImplode($more);
		$_SESSION['diffen'][$key] = array('lack' => $lack, 'more' => $more);			
		
		//判断顺序是否一致
		foreach ($maintable as $kk => $vv){
			$main[$kk] = $vv[0];
		}
		foreach ($value as $kk => $vv){
			$bb[$kk] = $vv[0];
		}
		
		if(array_diff_assoc($main, $bb)){
			$diffen[$key]['lack'] = "<font color=green>字段顺序不一致</font> <br/>".$diffen[$key]['lack'];
		}
		
		if ($diffen[$key]['lack'] == '') {
			$diffen[$key]['lack'] = '一致';
		}
		if ($diffen[$key]['more'] == '') {
			$diffen[$key]['more'] = '一致';
		}
		

	}
	return $diffen;
}

/*处理比较结果,生成显示内容
 *@ param $diffen      比较的结果
 *@ param $mainTab     主表
 *@ param $dbId        库id
*/
function showCompare ($diffen, $mainTab, $dbId){
	$html = "<br> <div align=center><input type='checkbox' id='is_back' name='is_back' value='1' checked><font color=red >是否备份</font> 主表为{$mainTab},以下为比较结果:</div><table width=\"800\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\"><tr><th>表名</th><th>缺少字段</th><th>多余字段</th><th>操作</th></tr>";
	foreach ($diffen as $key => $value){
		$html .= "<tr><td>$key</td><td> {$value['lack']}</td><td>{$value['more']}</td>";
		//同步操作链接
		if ($value['lack'] != '一致' || $value['more'] != '一致') {
			$html .= "<td><a href='#' onclick=\"if(confirm('确定同步字段吗?')) asynTable('tabfield', '{$key}', '{$mainTab}', '{$dbId}');\">同步</a></td></tr>";
		}else {
			$html .= "<td></td></tr>";
		}
	}
	$html .= "</table>";
	return $html;
}

/* 连接数据库
*/
/*function my_mysqlline ($dbId, $dbmainId){
	//获取数据库id 连接数据库
	if (strstr($dbId, '|') && $dbmainId != '') {
		$Arr  = explode('|',$dbId);
		array_pop($Arr);
		$dbIds = $Arr;
		$dbIds[] = $dbmainId;
	}elseif (!strstr($dbId, '|') && $dbmainId != ''){
		$dbIds = array($dbId, $dbmainId);
	}else {
		$dbIds = $dbId; 		
	}
	$g_db = mysqlConnect($dbIds);	
	
	return $g_db;	
}*/
/*备份配置操作函数
 *@ param $diffen      比较的结果
 *@ param $mainTab     主表
 *@ param $dbId        库id
*/
function editConfig($filename, $str){
	$file = '../include/'.$filename;
	@chmod('include', 0777);
	@chmod($file, 0777);
	$num = @file_put_contents($file, $str);
	if ($num == 0) {
		exit('写入失败,可能是权限不足');
	}
}

/*远程比较数据库
 *@ param $dbdata               要比较的数据库数据
 *@ param $maindata             主数据库数据
*/
function compareNetDb ($dbdata, $maindata, $dbmainId){
	//比较数据库过程
	foreach ($dbdata as $key => $value){
		//与标准数据库比较,得出各种集合		
		$lack      = @array_diff_key($maindata[$dbmainId], $value);//缺少
		$more      = @array_diff_key($value, $maindata[$dbmainId]);//多余
		$intersect = @array_intersect_key($value, $maindata[$dbmainId]);//交集
		//用于同步表结构时判断
		$_SESSION['diff'][$key] = array('lack' => $lack, 'more' => $more, 'interset' => $intersect);
		
		//以下分别对三种集合进行处理
		foreach ($lack as $k => $val){
			$diffen[$key][$k] = array('exist' => '缺少', 'lack' => '未比较', 'more' => '未比较');
		}
		foreach ($more as $k => $val){
			$diffen[$key][$k] = array('exist' => '多余', 'lack' => '未比较', 'more' => '未比较');
		}
			
		foreach ($intersect as $k => $val){
			//字段对比
			$field_lack  = @array_udiff($maindata[$dbmainId][$k], $val, 'myDiff');//字段缺少
			$field_more  = @array_udiff($val, $maindata[$dbmainId][$k], 'myDiff');//字段多余	
			
			//用于同步字段时判断
			$_SESSION['diff'][$key]['field_lack'][$k] = $field_lack;		
			$_SESSION['diff'][$key]['field_more'][$k] = $field_more;				
			
			//判断顺序是否一致
			
			foreach ($maindata[$dbmainId][$k] as $kk => $vv){
				$main = array($kk => $vv[0]);
			}
			foreach ($val as $kk => $vv){
				$bb = array($kk => $vv[0]);
			}
			$order = '';
			$_SESSION['order'] = '';
			if(array_diff_assoc($main, $bb)){
				//$diffen[$key][$k]['exist'] = '字段顺序不一致';
				$order = '<font color=blue>字段顺序不一致</font>';
				$_SESSION['order'][$key][] = $k;
			}
			
			//返回字段及条数不一样的表结果
			if (count($field_lack) > 0 || count($field_more) > 0 ||$order) {
				
				$field_lack  = myImplode($field_lack);
				$field_more  = myImplode($field_more);
				$diffen[$key][$k] = array('exist' => '存在 '.$order, 'lack' => $field_lack, 'more' => $field_more); 
			}
			
		}
		
		if(count($intersect) > 0 && @count($diffen[$key]) == 0){
			$diffen[$key]['每张表及其结构'] = array('exist' => '完全一致', 'lack' => '', 'more' => '');
		}
		
	}
	return $diffen;
}
/*导出数据sql
 *@ param $tablename        表名
 *@ param $g_db             数据库标识
*/
function dataSql($tablename, $dbId){
	global $g_db;
	$sql = "SELECT * FROM $tablename";
	$row = $g_db[$dbId]->query($sql);

	if ($row->num_rows > 0) {
		$data_sql = '';
		while ($result = $row->fetch_array()){
			$data_sql .= "INSERT INTO $tablename (";
			$num = count($result)/2;			
			
			foreach ($result as $k => $val){
				if (!is_int($k)){
					$data_sql .= $k.',';
				}
			}
			$data_sql = substr($data_sql, 0, -1);
			$data_sql .= ') VALUES(';
			for ($i=0; $i<$num; $i++){
				$data_sql .= "'".addslashes($result[$i])."',";
			}
			$data_sql = substr($data_sql, 0, -1);
			$data_sql .= ");";
		}		
	}
	return empty($data_sql) ? false : $data_sql;
}

/**
 * 获取字段注释
 *
 * @param string $dbmainId 数据库标识
 * @param string $tablename 表名
 */

function getTableComment( $dbmainId , $tablename ){
	global $g_db, $g_db_conf;
	$version = $_SERVER['SERVER_NAME'];
	$sqlComment = "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '".$tablename."'##表名
AND table_schema = '".$g_db_conf[$version][$dbmainId]['db_name']."'##数据库名
";
	$rowCom = $g_db[$dbmainId]->query($sqlComment);
	if ( $g_db[$dbmainId]->errno ){
		printf("Errorcode: %d\n", $g_db[$dbId]->errno);
		exit('获取注释失败');
	}
	while ( $commnetResult = $rowCom->fetch_assoc() ){
		$commentArr[$commnetResult['COLUMN_NAME']] = $commnetResult['COLUMN_COMMENT'];
	}
	return $commentArr;
}

/**
 * 获取主库的所有表名
 *
 * @return $mainTables
 */
function getMainTables(){
	global $g_db, $configs;
	$g_db = mysqlConnect($configs['maindb']);
	$mainTables = array();
	$row = $g_db[$configs['maindb']]->query("show tables");
	while ( $result = $row->fetch_array()){
		$mainTables[] = $result[0];
	}
	return $mainTables;
}
?>